#include "http_server.h"
#include "html.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#define PASSWORD  "2760247189"

#define USERNAME "inori"
// 服务器文件根目录
#define FILE_ROOT "www"
#define MAX_FILES 100



// 初始化HTTP服务器
int http_server_init(http_server_t *server) {
    WSADATA wsa_data;
    if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0) {
        fprintf(stderr, "WSAStartup failed\n");
        return -1;
    }
    
    // 创建监听套接字
    server->listen_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (server->listen_socket == INVALID_SOCKET) {
        fprintf(stderr, "socket creation failed\n");
        return -1;
    }
    
    // 设置地址重用
    int reuse = 1;
    if (setsockopt(server->listen_socket, SOL_SOCKET, SO_REUSEADDR, 
                  (const char*)&reuse, sizeof(reuse)) < 0) {
        fprintf(stderr, "setsockopt failed\n");
        closesocket(server->listen_socket);
        return -1;
    }
    
    // 绑定地址和端口
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(SERVER_PORT);
    
    if (bind(server->listen_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        fprintf(stderr, "bind failed\n");
        closesocket(server->listen_socket);
        return -1;
    }
    
    // 开始监听
    if (listen(server->listen_socket, SOMAXCONN) < 0) {
        fprintf(stderr, "listen failed\n");
        closesocket(server->listen_socket);
        return -1;
    }
    
    // 初始化客户端套接字数组
    for (int i = 0; i < MAX_CLIENTS; i++) {
        server->client_sockets[i] = INVALID_SOCKET;
    }
    server->client_count = 0;
    
    printf("HTTP server started on port %d\n", SERVER_PORT);
    return 0;
}

// 发送HTTP响应
static void send_http_response(SOCKET client_socket, int status_code, 
                              const char *status_text, const char *content_type, 
                              const char *body, size_t body_length) {
    char header[1024];
    int header_len = snprintf(header, sizeof(header),
        "HTTP/1.1 %d %s\r\n"
        "Content-Type: %s\r\n"
        "Content-Length: %zu\r\n"
        "Connection: close\r\n"
        "\r\n",
        status_code, status_text, content_type, body_length);
    
    send(client_socket, header, header_len, 0);
    send(client_socket, body, body_length, 0);
}

// 处理子目录文件列表（支持 /files/<文件夹名> 路由）
void handle_subdirectory_list(SOCKET client_socket, const char *subpath) {
    // 构建完整目录路径（根目录 + 子目录）
    char full_dir[256];
    snprintf(full_dir, sizeof(full_dir), "%s/%s", FILE_ROOT, subpath);
    
    // 验证目录是否存在且为合法目录
    struct stat dir_stat;
    if (stat(full_dir, &dir_stat) != 0 || !S_ISDIR(dir_stat.st_mode)) {
        send_http_response(client_socket, 404, "Not Found", "text/html", not_found_html, strlen(not_found_html));
        return;
    }
    
    // 创建响应缓冲区
    char *response = malloc(10240); // 足够大的缓冲区
    if (!response) {
        send_http_response(client_socket, 500, "Internal Server Error", "text/plain", "Internal Server Error", 21);
        return;
    }
    
    // 复制HTML开始部分（包含返回上级目录的链接）
    size_t len = 0;
    // 先添加HTML头部
    len += snprintf(response + len, 10240 - len, "%s", file_list_html_start);
    // 添加"返回上级目录"链接（仅当不是根目录时）
    if (strcmp(subpath, "") != 0) {
        // 解析上级目录路径（简单处理：去掉最后一个目录层级）
        char parent_path[256] = "";
        char *last_slash = strrchr(subpath, '/');
        if (last_slash) {
            size_t parent_len = last_slash - subpath;
            strncpy(parent_path, subpath, parent_len);
            parent_path[parent_len] = '\0';
        }
        // 生成返回上级的HTML
        len += snprintf(response + len, 10240 - len,
            "<tr>"
            "<td><a href=\"/files/%s\" class=\"parent-link\">../</a></td>" // 上级目录链接
            "<td class=\"folder-size\">-</td>"
            "</tr>",
            parent_path);
    }
    
    // 打开子目录
    DIR *dir = opendir(full_dir);
    if (!dir) {
        char error_msg[256];
        snprintf(error_msg, sizeof(error_msg), "<tr><td colspan=\"2\">Failed to open directory: %s</td></tr>", subpath);
        len += snprintf(response + len, 10240 - len, "%s", error_msg);
    } else {
        // 遍历子目录中的文件和文件夹
        struct dirent *entry;
        while ((entry = readdir(dir)) != NULL) {
            // 跳过隐藏文件/目录和当前目录（.）、上级目录（..）
            if (entry->d_name[0] == '.') continue;
            
            // 构建条目完整路径
            char entry_path[256];
            snprintf(entry_path, sizeof(entry_path), "%s/%s", full_dir, entry->d_name);
            
            struct stat entry_stat;
            if (stat(entry_path, &entry_stat) == 0) {
                if (S_ISREG(entry_stat.st_mode)) {
                    // 处理文件：下载链接为 /download/<子目录>/<文件名>
                    double size = entry_stat.st_size;
                    const char *unit = "B";
                    if (size > 1024) { size /= 1024; unit = "KB"; }
                    if (size > 1024) { size /= 1024; unit = "MB"; }
                    
                    char file_line[512];
                    snprintf(file_line, sizeof(file_line),
                        "<tr>"
                        "<td><a href=\"/download/%s/%s\" class=\"file-link\">%s</a></td>"
                        "<td class=\"file-size\">%.2f %s</td>"
                        "</tr>",
                        subpath, entry->d_name, entry->d_name, size, unit);
                    len += snprintf(response + len, 10240 - len, "%s", file_line);
                } else if (S_ISDIR(entry_stat.st_mode)) {
                    // 处理子文件夹：链接为 /files/<当前子目录>/<子文件夹名>
                    char folder_line[512];
                    snprintf(folder_line, sizeof(folder_line),
                        "<tr>"
                        "<td><a href=\"/files/%s/%s\" class=\"folder-link\">%s/</a></td>"
                        "<td class=\"folder-size\">-</td>"
                        "</tr>",
                        subpath, entry->d_name, entry->d_name);
                    len += snprintf(response + len, 10240 - len, "%s", folder_line);
                }
            }
        }
        closedir(dir);
    }
    
    // 拼接HTML结束部分
    len += snprintf(response + len, 10240 - len, "%s", file_list_html_end);
    
    // 发送响应
    send_http_response(client_socket, 200, "OK", "text/html", response, len);
    free(response);
}
// 处理登录请求
static void handle_login_request(SOCKET client_socket, const http_message_t *request) {
    // 获取表单数据
    const char *username = NULL;
    const char *password = NULL;
    
    if (request->body_length > 0) {
        char *body = strdup(request->body);
        char *token = strtok(body, "&");
        while (token) {
            char *eq = strchr(token, '=');
            if (eq) {
                *eq = '\0';
                char *key = token;
                char *value = eq + 1;
                
                if (strcmp(key, "username") == 0) {
                    username = value;
                } else if (strcmp(key, "password") == 0) {
                    password = value;
                }
            }
            token = strtok(NULL, "&");
        }
    }
        // 简单的登录验证
    if (username && password && strcmp(username, USERNAME) == 0 && strcmp(password, PASSWORD) == 0) {
        // 登录成功 - 重定向到文件列表
        const char *redirect = 
            "HTTP/1.1 302 Found\r\n"
            "Location: /files\r\n"
            "Content-Length: 0\r\n"
            "Connection: close\r\n"
            "\r\n";
        send(client_socket, redirect, strlen(redirect), 0);
    } else {
        // 登录失败
        send_http_response(client_socket, 401, "Unauthorized", "text/html", failure_html, strlen(failure_html));
    }
}

// 处理HTTP请求
void handle_http_request(SOCKET client_socket, const char *request, size_t length) {
    // 解析HTTP请求
    http_message_t *msg = http_parse(request, length);
    if (!msg) {
        send_http_response(client_socket, 400, "Bad Request", "text/plain", "Bad Request", 11);
        return;
    }
    printf("method : %s path : %s  type: %d\r\n",http_method_str(msg->method),msg->base_path,msg->type);
    // 根据请求路径和方法处理请求
    if (msg->type == HTTP_TYPE_REQUEST ) {
        if(strcmp(msg->base_path,"/api") == 0){
            char * rpt = "Hello, world!";
            send_http_response(client_socket, 200, "OK", "text/html", rpt, strlen(rpt));
        }
        else if(strcmp(msg->base_path, "/") == 0 && msg->method == HTTP_METHOD_GET) {
            send_http_response(client_socket, 200, "OK", "text/html", html_content, strlen(html_content));
        }
        else if (strcmp(msg->base_path, "/login") == 0 && msg->method == HTTP_METHOD_GET) {
            // 返回登录页面
            send_http_response(client_socket, 200, "OK", "text/html", login_html, strlen(login_html));
        } 
        else if (strcmp(msg->base_path, "/login_in") == 0 && msg->method == HTTP_METHOD_POST) {
            // 处理登录请求
            handle_login_request(client_socket, msg);
        }
        else if (strncmp(msg->base_path, "/files", 6) == 0 && msg->method == HTTP_METHOD_GET) {
            // 提取子路径（去掉 "/files" 部分）
            const char *subpath = msg->base_path + 6;
            // 如果路径是 "/files" 或 "/files/"，默认展示根目录
            if (subpath[0] == '\0' || (subpath[0] == '/' && subpath[1] == '\0')) {
                handle_file_list(client_socket); // 原根目录处理函数
            } else {
                // 去掉子路径开头的 '/'（如 "/subdir" -> "subdir"）
                if (subpath[0] == '/') subpath++;
                handle_subdirectory_list(client_socket, subpath); // 子目录处理函数
            }
        }
        else if (strcmp(msg->base_path, "/upload") == 0 && msg->method == HTTP_METHOD_GET) {
            // 显示文件列表（包含上传表单）
            handle_file_list(client_socket);
        }
        else if (strcmp(msg->base_path, "/upload") == 0 && msg->method == HTTP_METHOD_POST) {
            // 处理文件上传
            handle_file_upload(client_socket, msg);
        }
        else if (strncmp(msg->base_path, "/download/", 10) == 0 && msg->method == HTTP_METHOD_GET) {
            // 处理文件下载
            handle_file_download(client_socket, msg->base_path + 10);
        }

        else {
            // 返回404
            printf("path not found\n");
            send_http_response(client_socket, 404, "Not Found", "text/html", not_found_html, strlen(not_found_html));
        }
    } else {
        // 只处理请求，不处理响应
        printf("not a request\n");
        send_http_response(client_socket, 400, "Bad Request", "text/plain", "Expected HTTP request", 19);
    }
    
    // 清理消息
    http_message_free(msg);
}

// 运行HTTP服务器
void http_server_run(http_server_t *server) {
    while (1) {
        // 初始化文件描述符集合
        FD_ZERO(&server->read_fds);
        FD_SET(server->listen_socket, &server->read_fds);
        
        SOCKET max_sd = server->listen_socket;
        
        // 添加客户端套接字
        for (int i = 0; i < MAX_CLIENTS; i++) {
            SOCKET sd = server->client_sockets[i];
            if (sd != INVALID_SOCKET) {
                FD_SET(sd, &server->read_fds);
                if (sd > max_sd) max_sd = sd;
            }
        }
        
        // 等待活动
        int activity = select(max_sd + 1, &server->read_fds, NULL, NULL, NULL);
        if (activity < 0 && WSAGetLastError() != WSAEINTR) {
            fprintf(stderr, "select error\n");
            break;
        }
        
        // 处理新的连接
        if (FD_ISSET(server->listen_socket, &server->read_fds)) {
            struct sockaddr_in client_addr;
            int addr_len = sizeof(client_addr);
            SOCKET new_socket = accept(server->listen_socket, 
                                      (struct sockaddr*)&client_addr, &addr_len);
            if (new_socket == INVALID_SOCKET) {
                fprintf(stderr, "accept failed\n");
                continue;
            }
            
            // 添加到客户端列表
            int added = 0;
            for (int i = 0; i < MAX_CLIENTS; i++) {
                if (server->client_sockets[i] == INVALID_SOCKET) {
                    server->client_sockets[i] = new_socket;
                    server->client_count++;
                    added = 1;
                    break;
                }
            }
            
            if (!added) {
                fprintf(stderr, "Too many clients, connection closed\n");
                closesocket(new_socket);
            }
        }
        
        // 处理客户端数据
        for (int i = 0; i < MAX_CLIENTS; i++) {
            SOCKET sd = server->client_sockets[i];
            if (sd != INVALID_SOCKET && FD_ISSET(sd, &server->read_fds)) {
                char buffer[BUFFER_SIZE];
                int bytes_received = recv(sd, buffer, sizeof(buffer), 0);
                
                if (bytes_received <= 0) {
                    // 连接关闭或出错
                    closesocket(sd);
                    server->client_sockets[i] = INVALID_SOCKET;
                    server->client_count--;
                } else {
                    // 处理HTTP请求
                    handle_http_request(sd, buffer, bytes_received);
                    
                    // 关闭连接（HTTP/1.0风格）
                    closesocket(sd);
                    server->client_sockets[i] = INVALID_SOCKET;
                    server->client_count--;
                }
            }
        }
    }
}

// 清理HTTP服务器
void http_server_cleanup(http_server_t *server) {
    // 关闭所有客户端套接字
    for (int i = 0; i < MAX_CLIENTS; i++) {
        if (server->client_sockets[i] != INVALID_SOCKET) {
            closesocket(server->client_sockets[i]);
        }
    }
    
    // 关闭监听套接字
    if (server->listen_socket != INVALID_SOCKET) {
        closesocket(server->listen_socket);
    }
    
    // 清理Winsock
    WSACleanup();
}
// 处理文件列表
void handle_file_download(SOCKET client_socket, const char *path) {
    // 构建完整文件路径（根目录 + 子路径 + 文件名）
    char full_path[256];
    snprintf(full_path, sizeof(full_path), "%s/%s", FILE_ROOT, path);
    
    // 打开文件（后续逻辑与原函数一致）
    FILE *file = fopen(full_path, "rb");
    if (!file) {
        send_http_response(client_socket, 404, "Not Found", "text/html", not_found_html, strlen(not_found_html));
        return;
    }
    
    // 获取文件大小
    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    fseek(file, 0, SEEK_SET);
    
    // 读取文件内容
    char *buffer = malloc(file_size);
    if (!buffer) {
        fclose(file);
        send_http_response(client_socket, 500, "Internal Server Error", "text/plain", "Internal Server Error", 21);
        return;
    }
    
    size_t bytes_read = fread(buffer, 1, file_size, file);
    fclose(file);
    
    if (bytes_read != (size_t)file_size) {
        free(buffer);
        send_http_response(client_socket, 500, "Internal Server Error", "text/plain", "Internal Server Error", 21);
        return;
    }
    
    // 根据文件扩展名设置Content-Type
    const char *content_type = "application/octet-stream";
    const char *ext = strrchr(path, '.');
    if (ext) {
        if (strcmp(ext, ".html") == 0 || strcmp(ext, ".htm") == 0) {
            content_type = "text/html";
        } else if (strcmp(ext, ".css") == 0) {
            content_type = "text/css";
        } else if (strcmp(ext, ".js") == 0) {
            content_type = "application/javascript";
        } else if (strcmp(ext, ".jpg") == 0 || strcmp(ext, ".jpeg") == 0) {
            content_type = "image/jpeg";
        } else if (strcmp(ext, ".png") == 0) {
            content_type = "image/png";
        } else if (strcmp(ext, ".gif") == 0) {
            content_type = "image/gif";
        } else if (strcmp(ext, ".pdf") == 0) {
            content_type = "application/pdf";
        } else if (strcmp(ext, ".txt") == 0) {
            content_type = "text/plain";
        } else if (strcmp(ext, ".svg") == 0) {
            content_type = "image/svg+xml";
        } else if (strcmp(ext, ".json") == 0) {
            content_type = "application/json";
        } else if (strcmp(ext, ".xml") == 0) {
            content_type = "application/xml";
        } else if (strcmp(ext, ".mp3") == 0) {
            content_type = "audio/mpeg";
        } else if (strcmp(ext, ".mp4") == 0) {
            content_type = "video/mp4";
        } else if (strcmp(ext, ".webp") == 0) {
            content_type = "image/webp";
        }
        else if (strcmp(ext, ".docx") == 0) {
            content_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        } else if (strcmp(ext, ".zip") == 0) {
            content_type = "application/zip";
        } else if (strcmp(ext, ".tar") == 0) {
            content_type = "application/x-tar";
        } else if (strcmp(ext, ".bmp") == 0) {
            content_type = "image/bmp";
        } else if (strcmp(ext, ".xlsx") == 0) {
            content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        } else if (strcmp(ext, ".ppt") == 0) {
            content_type = "application/vnd.ms-powerpoint";
        }
        else if (strcmp(ext, ".avi") == 0) {
            content_type = "video/x-msvideo";
        } else if (strcmp(ext, ".mov") == 0) {
            content_type = "video/quicktime";
        } else if (strcmp(ext, ".wmv") == 0) {
            content_type = "video/x-ms-wmv";
        } else if (strcmp(ext, ".flv") == 0) {
            content_type = "video/x-flv";
        } else if (strcmp(ext, ".mkv") == 0) {
            content_type = "video/x-matroska";
        } else if (strcmp(ext, ".ogg") == 0) {
            content_type = "audio/ogg";
        } else if (strcmp(ext, ".wav") == 0) {
            content_type = "audio/wav";
        } else if (strcmp(ext, ".ico") == 0) {
            content_type = "image/x-icon";
        } else if (strcmp(ext, ".tiff") == 0 || strcmp(ext, ".tif") == 0) {
            content_type = "image/tiff";
        } else if (strcmp(ext, ".eps") == 0) {
            content_type = "application/postscript";
        } else if (strcmp(ext, ".rtf") == 0) {
            content_type = "application/rtf";
        } else if (strcmp(ext, ".xls") == 0) {
            content_type = "application/vnd.ms-excel";
        } else if (strcmp(ext, ".pptx") == 0) {
            content_type = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        } else if (strcmp(ext, ".ods") == 0) {
            content_type = "application/vnd.oasis.opendocument.spreadsheet";
        } else if (strcmp(ext, ".odt") == 0) {
            content_type = "application/vnd.oasis.opendocument.text";
        }
        // 处理.cae文件
        if (strcmp(ext, ".cae") == 0) {
            char *html_response = malloc(10240 + file_size);
            if (!html_response) {
                free(buffer);
                send_http_response(client_socket, 500, "Internal Server Error", "text/plain", "Internal Server Error", 21);
                return;
            }

            int len = snprintf(html_response, 10240 + file_size, 
               file_list_html_cab, buffer);

            content_type = "text/html";
            send_http_response(client_socket, 200, "OK", content_type, html_response, len);
            free(html_response);
        } else {
            // 其他文件类型正常下载
            send_http_response(client_socket, 200, "OK", content_type, buffer, file_size);
        }
    } else {
        // 无扩展名文件正常下载
        send_http_response(client_socket, 200, "OK", content_type, buffer, file_size);
    }
    
    free(buffer);
}
void handle_file_upload(SOCKET client_socket, const http_message_t *request) {


    // 检查请求体是否为空
    if (request->body_length == 0) {
        //printf("错误：请求体为空，可能是客户端未发送文件\n");
        char response[1024];
        snprintf(response, sizeof(response), upload_failure_html, "No file uploaded (empty request)");
        send_http_response(client_socket, 400, "Bad Request", "text/html", response, strlen(response));
        return;
    }

    // 获取Content-Type头部
    const char *content_type = http_get_header(request, HTTP_HEADER_CONTENT_TYPE);
    if (!content_type || strstr(content_type, "multipart/form-data") == NULL) {
        // 错误处理...
        return;
    }

    // 解析boundary（优化版）
    const char *boundary_start = strstr(content_type, "boundary=");
    if (!boundary_start) { /* 错误处理... */ return; }
    boundary_start += 9;
    char boundary[100] = {0};
    const char *boundary_end = strchr(boundary_start, ';');
    size_t boundary_len = boundary_end ? (boundary_end - boundary_start) : strlen(boundary_start);
    boundary_len = (boundary_len >= sizeof(boundary)-1) ? sizeof(boundary)-1 : boundary_len;
    strncpy(boundary, boundary_start, boundary_len);

    // 构建完整边界（兼容标准格式）
    char full_boundary[120];
    snprintf(full_boundary, sizeof(full_boundary), "\r\n--%s", boundary);
    char *body_start = (char *)request->body;
    char *boundary_ptr = strstr(body_start, full_boundary);
    if (!boundary_ptr) {
        snprintf(full_boundary, sizeof(full_boundary), "--%s", boundary); // 尝试不带\r\n
        boundary_ptr = strstr(body_start, full_boundary);
        if (!boundary_ptr) { /* 错误处理... */ return; }
    }

    
    // 查找Content-Disposition
    char *disposition_start = strstr(boundary_ptr, "Content-Disposition:");
    if (!disposition_start) {
        char response[1024];
        int len = snprintf(response, sizeof(response), upload_failure_html, "Content-Disposition missing");
        send_http_response(client_socket, 400, "Bad Request", "text/html", response, len);
        return;
    }
    
    // 查找文件名
    char *filename_start = strstr(disposition_start, "filename=\"");
    if (!filename_start) {
        char response[1024];
        int len = snprintf(response, sizeof(response), upload_failure_html, "Filename missing");
        send_http_response(client_socket, 400, "Bad Request", "text/html", response, len);
        return;
    }
    
    filename_start += 10; // 跳过 "filename=\""
    char *filename_end = strchr(filename_start, '"');
    if (!filename_end) {
        char response[1024];
        int len = snprintf(response, sizeof(response), upload_failure_html, "Invalid filename format");
        send_http_response(client_socket, 400, "Bad Request", "text/html", response, len);
        return;
    }
    
    // 提取文件名
    size_t filename_len = filename_end - filename_start;
    char filename[256];
    if (filename_len >= sizeof(filename)) filename_len = sizeof(filename) - 1;
    strncpy(filename, filename_start, filename_len);
    filename[filename_len] = '\0';
    
    // 查找文件内容的开始位置
    char *file_start = strstr(filename_end, "\r\n\r\n");
    if (!file_start) {
        char response[1024];
        int len = snprintf(response, sizeof(response), upload_failure_html, "File content not found");
        send_http_response(client_socket, 400, "Bad Request", "text/html", response, len);
        return;
    }
    
    file_start += 4; // 跳过 "\r\n\r\n"
    
    // 查找文件内容的结束位置
    char *file_end = strstr(file_start, full_boundary);
    if (!file_end) {
        char response[1024];
        int len = snprintf(response, sizeof(response), upload_failure_html, "File end not found");
        send_http_response(client_socket, 400, "Bad Request", "text/html", response, len);
        return;
    }
    
    // 确保file_end在请求体范围内
    if (file_end > body_start + request->body_length) {
        char response[1024];
        int len = snprintf(response, sizeof(response), upload_failure_html, "File extends beyond body");
        send_http_response(client_socket, 400, "Bad Request", "text/html", response, len);
        return;
    }
    
    // 计算文件大小
    size_t file_size = file_end - file_start;
    if (file_end[-2] == '\r' && file_end[-1] == '\n') {
        file_size -= 2; // 去掉结尾的\r\n
    } else if (file_end[-1] == '\n') {
        file_size -= 1; // 去掉结尾的\n
    }
    
    // 创建文件根目录（如果不存在）
    struct stat st = {0};
    if (stat(FILE_ROOT, &st) == -1) {
        mkdir(FILE_ROOT);
    }
    
    // 构建完整文件路径
    char full_path[256];
    snprintf(full_path, sizeof(full_path), "%s/%s", FILE_ROOT, filename);
    
    // 保存文件
    FILE *file = fopen(full_path, "wb");
    if (!file) {
        char response[1024];
        int len = snprintf(response, sizeof(response), upload_failure_html, "Failed to create file");
        send_http_response(client_socket, 500, "Internal Server Error", "text/html", response, len);
        return;
    }
    
    size_t bytes_written = fwrite(file_start, 1, file_size, file);
    fclose(file);
    
    if (bytes_written != file_size) {
        remove(full_path); // 删除不完整的文件
        char response[1024];
        int len = snprintf(response, sizeof(response), upload_failure_html, "Failed to write file");
        send_http_response(client_socket, 500, "Internal Server Error", "text/html", response, len);
        return;
    }
    
    // 上传成功
    send_http_response(client_socket, 200, "OK", "text/html", upload_success_html, strlen(upload_success_html));
}
// 处理文件列表
// 处理文件列表
void handle_file_list(SOCKET client_socket) {
    // 创建响应缓冲区
    char *response = malloc(10240); // 足够大的缓冲区
    if (!response) {
        send_http_response(client_socket, 500, "Internal Server Error", "text/plain", "Internal Server Error", 21);
        return;
    }

    // 复制HTML开始部分
    size_t len = strlen(file_list_html_start);
    memcpy(response, file_list_html_start, len);

    // 创建文件根目录（如果不存在）
    struct stat st = {0};
    if (stat(FILE_ROOT, &st) == -1) {
        mkdir(FILE_ROOT);
    }

    // 打开目录
    DIR *dir = opendir(FILE_ROOT);
    if (!dir) {
        char error_msg[256];
        snprintf(error_msg, sizeof(error_msg), "<tr><td colspan=\"2\">Failed to open directory</td></tr>");
        strcat(response, error_msg);
        len += strlen(error_msg);
    } else {
        // 遍历目录中的文件和文件夹
        struct dirent *entry;
        while ((entry = readdir(dir)) != NULL) {
            // 跳过隐藏文件和目录
            if (entry->d_name[0] == '.') continue;

            // 获取文件信息
            char full_path[256];
            snprintf(full_path, sizeof(full_path), "%s/%s", FILE_ROOT, entry->d_name);

            struct stat file_stat;
            if (stat(full_path, &file_stat) == 0) {
                if (S_ISREG(file_stat.st_mode)) {
                    // 处理文件
                    double size = file_stat.st_size;
                    const char *unit = "B";
                    if (size > 1024) {
                        size /= 1024;
                        unit = "KB";
                    }
                    if (size > 1024) {
                        size /= 1024;
                        unit = "MB";
                    }

                    // 添加文件行
                    char file_line[512];
                    snprintf(file_line, sizeof(file_line),
                        "<tr>"
                        "<td><a href=\"/download/%s\" class=\"file-link\">%s</a></td>"
                        "<td class=\"file-size\">%.2f %s</td>"
                        "</tr>",
                        entry->d_name, entry->d_name, size, unit);

                    strcat(response, file_line);
                    len += strlen(file_line);
                } else if (S_ISDIR(file_stat.st_mode)) {
                    // 处理文件夹
                    char folder_line[512];
                    snprintf(folder_line, sizeof(folder_line),
                        "<tr>"
                        "<td><a href=\"/files/%s\" class=\"folder-link\">%s/</a></td>"
                        "<td class=\"folder-size\">-</td>"
                        "</tr>",
                        entry->d_name, entry->d_name);

                    strcat(response, folder_line);
                    len += strlen(folder_line);
                }
            }
        }
        closedir(dir);
    }

    // 复制HTML结束部分
    strcat(response, file_list_html_end);
    len += strlen(file_list_html_end);

    // 发送响应
    send_http_response(client_socket, 200, "OK", "text/html", response, len);
    free(response);
}